<template>
  <y-dialog @close="emit('close')" width="1000px" append-to-body>
    <div style="display: flex; justify-content: flex-end">
      <el-tooltip content="同步用例即自动更新用例，这将包括用例的所有信息，为保证过程可信，请慎用！" placeholder="top">
        <el-switch v-model="syncCases" inline-prompt active-text="开启同步用例" inactive-text="关闭同步用例"></el-switch>
      </el-tooltip>
    </div>
    <el-table ref="retryRef" :data="props.data" row-key="id" :tree-props="{ children: treePropsChildren }"
      @selection-change="handleSelectionChange" @select="handleRowSelect" @select-all="handleSelectAll"
      :select-on-indeterminate="false" :row-class-name="tableRowClassName" border style="width: 100%" max-height="800">
      <el-table-column type="selection" width="55" />
      <el-table-column label="用例编号" prop="number" :show-overflow-tooltip="true" />
      <el-table-column label="用例名称" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="用例步骤" v-if="props.level === '1' && !syncCases" align="center">
        <el-table-column label="描述" prop="step" :show-overflow-tooltip="true" />
        <el-table-column label="预期值" prop="exp" :show-overflow-tooltip="true" />
        <el-table-column label="实际值" prop="actual" :show-overflow-tooltip="true">
          <template #default="scope">
            <span>{{ scope.row.actual }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结果" prop="result" width="80">
          <template #default="scope">
            <y-dict-tag :options="tms_tc_result" :value="scope.row.result" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="执行结果" prop="status" width="100">
        <template #default="scope">
          <y-dict-tag :options="tms_job_status" :value="scope.row.status" />
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="emit('close')">取消</el-button>
      </div>
    </template>
  </y-dialog>
</template>

<script setup name="Retry">
import { retryJob } from "@/api/tms/job";
import useUserStore from "@/store/modules/user";

const route = useRoute();
const { proxy } = getCurrentInstance();

const emit = defineEmits(["submited", "close"]);

const { tms_job_status, tms_tc_result } = proxy.useDict(
  "tms_job_status",
  "tms_tc_result"
);

const props = defineProps({
  data: { type: Array, default: undefined },
  level: { type: String, default: "0" },
  updateJobLog: { type: Function, default: undefined },
});

const ids = ref([]);
const multiple = ref(true);
const selected = ref([]);
const syncCases = ref(false);

const treePropsChildren = computed(() => {
  return props.level === "1" && !syncCases.value ? "steps" : null;
});

/**多选框选中数据操作 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  multiple.value = !selection.length;
  selected.value = selection.map((item) => item);
}

/** 当用户手动勾选数据行的 Checkbox 时触发的事件 */
function handleRowSelect(selection, row) {
  if (
    selection.some((el) => {
      return row.id === el.id;
    })
  ) {
    // 选中情况下处理逻辑
    if (row.steps) {
      // 选中用例节点处理逻辑
      row.steps.map((j) => {
        toggleSelection(j, true);
      });
    } else {
      // 选中步骤节点处理逻辑
      let testcase = props.data.find((x) => row.id.includes(x.id));
      toggleSelection(testcase, true);
    }
  } else {
    // 取消选中情况下处理逻辑
    if (row.steps) {
      // 取消用例节点处理逻辑
      row.steps.map((j) => {
        toggleSelection(j, false);
      });
    } else {
      // 取消步骤节点处理逻辑
      let testcase = props.data.find((x) => row.id.includes(x.id));
      let steps = selection.find((x) => x.id.includes(testcase.id + "_"));
      if (!steps) {
        toggleSelection(testcase, false);
      }
    }
  }
}

/** 当用户手动勾选全选 Checkbox 时触发的事件 */
function handleSelectAll(selection) {
  // 第一层只要有在selection里面就是全选
  const isSelect = selection.some((el) => {
    const tableDataIds = props.data.map((j) => j.id);
    return tableDataIds.includes(el.id);
  });
  // 第一层只要有不在selection里面就是全不选
  const isCancel = !props.data.every((el) => {
    const selectIds = selection.map((j) => j.id);
    return selectIds.includes(el.id);
  });
  if (isSelect) {
    selection.map((el) => {
      if (el.steps) {
        el.steps.map((j) => {
          toggleSelection(j, true);
        });
      }
    });
  }
  if (isCancel) {
    props.data.map((el) => {
      if (el.steps) {
        el.steps.map((j) => {
          toggleSelection(j, false);
        });
      }
    });
  }
}

function tableRowClassName({ row, index }) {
  let count = ids.value.filter((x) => x.includes(row.id + "_")).length;
  if (row.steps && 0 < count && count < row.steps.length) {
    return "indeterminate";
  } else {
    return "";
  }
}

function toggleSelection(row, select) {
  if (row) {
    proxy.$nextTick(() => {
      proxy.$refs.retryRef &&
        proxy.$refs.retryRef.toggleRowSelection(row, select);
    });
  }
}

/** 提交按钮事件 */
function submit() {
  try {
    proxy.$modal
      .confirm("重试过程会覆盖原有结果，确认要重试吗？")
      .then(function () {
        useUserStore()
          .getInfo()
          .then((res) => {
            ids.value = syncCases.value
              ? ids.value.filter((item) => !/_\d+$/.test(item))
              : ids.value;
            retryJob(route.query.job, {
              job_execution: route.query.job_execution,
              testcases: ids.value,
              sync_case: syncCases.value,
              executor: res.data.user.id,
            }).then(() => {
              proxy.$modal.msgSuccess("开始重试任务");
              submited();
            });
          });
      });
  } catch (err) {
    proxy.$modal.msgError(`操作失败，失败原因请参考：${err}`);
  }
}

/** submited事件 */
function submited() {
  emit("submited");
  emit("close");
}
</script>

<style>
.indeterminate .el-table-column--selection .cell .el-checkbox {
  display: block !important;
}

.indeterminate .el-checkbox__input .el-checkbox__inner {
  background-color: #4a97eb !important;
  border-color: #4a97eb !important;
  color: #fff !important;
}

.indeterminate .el-checkbox__input.is_checked .el-checkbox__inner::after {
  translate: scale(0.5);
}

.indeterminate .el-checkbox__input .el-checkbox__inner::after {
  border-color: #c0c4cc !important;
  background-color: #c0c4cc;
}

.indeterminate .el-checkbox__input .el-checkbox__inner::after {
  content: "";
  position: absolute;
  display: block;
  background-color: #fff;
  height: 2px;
  transform: scale(0.5);
  left: 0;
  right: 0;
  top: 5px;
  width: auto !important;
}
</style>
